package com.zhkj.txg.module.member.ui

import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.txg.R
import com.zhkj.txg.module.member.adapter.MemberInviteAdapter
import com.zhkj.txg.module.member.vm.MemberListViewModel
import kotlinx.android.synthetic.main.fragment_collection.*

class MemberInviteFragment : ViewModelFragment<MemberListViewModel>() {

    companion object {
        private val TYPE = "type"
        fun newInstance(type: Int): MemberInviteFragment = MemberInviteFragment().apply {
            arguments = bundleOf(Pair(TYPE, type))
        }
    }

    override fun setViewModel(): MemberListViewModel = createViewModel(false)
    override val layoutResId: Int = R.layout.fragment_collection

    private val inviteAdapter = MemberInviteAdapter().apply {
        loadMoreModule?.setOnLoadMoreListener { initData() }
    }

    override fun initUI() {
        with(rvCollection) {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = inviteAdapter
            addItemDecoration(DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL).apply {
                val drawable = ContextCompat.getDrawable(requireContext(), R.drawable.divider_vertical_1)
                if (drawable != null) setDrawable(drawable)
            })
        }
        inviteAdapter.setEmptyView(R.layout.layout_empty_data)
        refreshCollection.setOnRefreshListener { initData() }
    }

    override fun initData() {
        val type = arguments?.getInt(TYPE) ?: 0
        viewModel.inviteList(type)
    }

    override fun initViewModel() {
        viewModel.inviteListLiveData.observe(viewLifecycleOwner, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    // 判断加载状态
                    if (!it.loadMore) refreshCollection.finishRefresh()
                    else if (it.hasMore) inviteAdapter.loadMoreModule?.loadMoreComplete()
                    else inviteAdapter.loadMoreModule?.loadMoreEnd()
                    // 数据填充
                    if (it.loadMore) inviteAdapter.addData(it.data)
                    else inviteAdapter.setNewData(it.data)
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                    if (viewModel.page > 1) inviteAdapter.loadMoreModule?.loadMoreFail()
                    else refreshCollection.finishRefresh(false)
                }
            }
        })
    }
}